package com.smartstate.dataManagement.schedul;//package com.smartstate.EnvironmentMonitor.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.GsonBuilder;
import com.smartstate.dataManagement.dto.RealTimeDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/webSocket/{userId}")
@Component
public class WebSocketCopy {


    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象。
    public static ConcurrentHashMap<String, WebSocketCopy> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private void setSession(Session session) {
        this.session = session;
    }

    private String userId;

    public static RealTimeDTO dataDTO;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        this.session = session;
        this.userId = userId;
        webSocketMap.put(userId, this);
        sendMessage("连接成功" , userId);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(this.userId);
        log.info("有一连接关闭！");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param str 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String str) {
//        将String类型的json数据，进行格式化
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        try {
            dataDTO = gson.fromJson(str, RealTimeDTO.class);
        }catch (Exception e){
            log.info("输入数据格式有误");
            return;
        }
        if (dataDTO == null) {
            return;
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        webSocketMap.remove(this.userId);
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object message, String userId) {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现服务器主动群发消息
     */
    public static void sendInfo(Object message) {
        for (Map.Entry<String, WebSocketCopy> item : webSocketMap.entrySet()) {
            item.getValue().sendMessage(message, item.getKey());
        }
    }

    public static void send(Object message, String userId) {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

